import { Form, Input, Modal } from 'antd'
import { useEffect } from 'react'
import { BigCar, addOrUp } from '../services'
import { useRequest } from 'ahooks'

export interface EditModalProps {
  open: boolean
  type?: 'add' | 'edit'
  record?: BigCar
  onCancel?: (refresh: boolean) => void
}

const EditModal: React.FC<EditModalProps> = props => {
  const [editForm] = Form.useForm()
  const { runAsync, loading } = useRequest(addOrUp, {manual: true})

  const onCancel = (refresh: boolean) => {
    editForm.resetFields()
    props.onCancel?.(refresh)
  }

  const onOk = () => {
    editForm.validateFields()
      .then((formValues: any) => {
        return runAsync(formValues)
      })
      .then(() => {
        onCancel(true)
      })
  }

  useEffect(() => {
    if (props.open && props.record) {
      editForm.setFieldsValue({
        companyCarId: props.record.id,
        carPlat: props.record.carPlat,
        infoName: props.record.infoName,
        vin: props.record.vin,
      })
    }
  }, [props.open])

  return (
    <Modal
      title={props.type === 'add' ? '添加车辆' : '编辑车辆'}
      open={props.open}
      onOk={onOk}
      onCancel={() => onCancel(false)}
      destroyOnClose
      confirmLoading={loading}
    >
      <Form name='editBigCarForm' form={editForm} labelCol={{flex: '80px'}}>
        <Form.Item name='companyCarId' noStyle><Input hidden /></Form.Item>
        <Form.Item label='车牌号' name='carPlat' rules={[{required: true, message: '请输入车牌号'}]}>
          <Input placeholder='请输入' />
        </Form.Item>
        <Form.Item label='别名' name='infoName'>
          <Input placeholder='请输入' />
        </Form.Item>
        <Form.Item label='vin码' name='vin'>
          <Input placeholder='请输入' />
        </Form.Item>
      </Form>
    </Modal>
  )
}

export default EditModal
